from apscheduler.schedulers.background import BackgroundScheduler
from adapters.data_source_adapter import DataSourceAdapter
from .data_storage import DataStorage
import logging

class DataCollector:
    def __init__(self, adapter: DataSourceAdapter, storage: DataStorage):
        self.adapter = adapter
        self.storage = storage
        self.scheduler = BackgroundScheduler()
        logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
        self.logger = logging.getLogger(__name__)

    def fetch_daily_data(self, symbols: list, start_date: str, end_date: str):
        try:
            for symbol in symbols:
                data = self.adapter.get_daily_data(symbol, start_date, end_date)
                if not data.empty:
                    self.storage.save_daily_data(data)
                    self.logger.info(f"Successfully fetched data for {symbol}")
        except Exception as e:
            self.logger.error(f"Failed to fetch data: {e}")

    def start_scheduler(self, symbols: list, start_date: str, end_date: str, interval: int):
        self.scheduler.add_job(
            self.fetch_daily_data,
            'interval',
            minutes=interval,
            args=[symbols, start_date, end_date]
        )
        self.scheduler.start()
